package com.sxm.yiwei.activitis;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.sxm.yiwei.MainActivity;
import com.sxm.yiwei.R;
import com.sxm.yiwei.adapters.VendorBookListAdapter;
import com.sxm.yiwei.beans.ServiceList;
import com.sxm.yiwei.tools.CallPhone;
import com.sxm.yiwei.tools.ErrType;
import com.sxm.yiwei.utils.InternetAddressUtis;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

public class VendorNoOverActivity extends BaseActivity implements View.OnClickListener{

    private ImageView nooverback;
    private PullToRefreshListView nooverlist;
    private SharedPreferences sharedPreferences;
    private String token;
    private String userId;
    private String appId;
    private int TYPE = 4;
    private String type = "1";
    private VendorBookListAdapter adapter;
    private ImageView nodata;
    private ImageView backmain;
    private  int from = 23;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_vendor_no_over);
        sharedPreferences = getSharedPreferences("userlogin", Context.MODE_PRIVATE);
        token = sharedPreferences.getString("token", "");
        userId = sharedPreferences.getString("userId", "");
        appId = sharedPreferences.getString("appid", "");
        initNoOverView();
        getNoOverList();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        getNoOverList();
    }

    // 卖家 已完成
    private void getNoOverList() {
        RequestParams params = new RequestParams(InternetAddressUtis.Url+InternetAddressUtis.GETVONDERSERVICELIST);
        params.addHeader("Content-Type","application/json");
        params.addHeader("token", token);
        params.addHeader("appId", appId);
        params.addHeader("userId", userId);
        JSONObject object = new JSONObject();
        object.put("status","3");
        params.addParameter("params",object.toJSONString());
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {


                getData(result);


            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ErrType.errType(VendorNoOverActivity.this,ex);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private void getData(String result) {


        JSONObject obj = JSON.parseObject(result);
        JSONArray data = obj.getJSONArray("data");
        List<ServiceList.DataBean> mlist = new ArrayList<>();
        if (data.size()==0){

        }else {
            nodata.setVisibility(View.GONE);
            for (int i = 0; i < data.size(); i++) {
                JSONObject obj1 = JSON.parseObject(String.valueOf(data.get(i)));
                String amount = obj1.getString("amount");
                String avatar = obj1.getString("avatar");
                String buyTime = obj1.getString("buyTime");
                String count = obj1.getString("count");
                String id = obj1.getString("id");
                String makeupCount = obj1.getString("makeupCount");
                String message = obj1.getString("message");
                String name = obj1.getString("name");
                String orderCode = obj1.getString("orderCode");
                String serviceId = obj1.getString("serviceId");
                String totalAmount = obj1.getString("totalAmount");
                String shopName = obj1.getString("shopName");
                String orderPayType = obj1.getString("orderPayType");
                String orderPayTime = obj1.getString("orderPayTime");
                String contactAddress = obj1.getString("contactAddress");
                String contactHouseNumber = obj1.getString("contactHouseNumber");
                String contactName = obj1.getString("contactName");
                String contactPhone = obj1.getString("contactPhone");
                String shopAddress = obj1.getString("shopAddress");
                String userMobile = obj1.getString("userMobile");
                ServiceList.DataBean dataBean = new ServiceList.DataBean();
                dataBean.setContactAddress(contactAddress);
                dataBean.setContactHouseNumber(contactHouseNumber);
                dataBean.setContactName(contactName);
                dataBean.setContactPhone(contactPhone);
                dataBean.setShopAddress(shopAddress);
                dataBean.setUserMobile(userMobile);
                dataBean.setAmount(Double.valueOf(amount));
                dataBean.setAvatar(avatar);
                dataBean.setBuyTime(Long.valueOf(buyTime));
                dataBean.setCount(Integer.valueOf(count));
                dataBean.setId(id);
                dataBean.setShopName(shopName);
                dataBean.setOrderPayTime(orderPayTime);
                dataBean.setOrderPayType(orderPayType);
                dataBean.setMakeupCount(Integer.valueOf(makeupCount));
                dataBean.setMessage(message);
                dataBean.setName(name);
                dataBean.setOrderCode(orderCode);
                dataBean.setServiceId(serviceId);
                dataBean.setTotalAmount(Double.valueOf(totalAmount));
                mlist.add(dataBean);
            }

        }

        adapter = new VendorBookListAdapter(VendorNoOverActivity.this,mlist,TYPE);
        nooverlist.setAdapter(adapter);
        adapter.setOnClickItemButtonListener(new VendorBookListAdapter.OnClickItemButtonListener() {
            @Override
            public void OnClickItemButtonListener(int position) {
                Toast.makeText(VendorNoOverActivity.this, "功能开发中，敬请期待", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void OnClickItemButtonListener1(int position) {
                String mobile = adapter.mlist.get(position).getContactPhone();
                CallPhone.callPhone(VendorNoOverActivity.this,mobile);
            }

            @Override
            public void OnClickItemButtonListener2(int position) {
                ServiceList.DataBean item = (ServiceList.DataBean) adapter.getItem(position);
                Intent intent = new Intent(VendorNoOverActivity.this,FWHiteMeShopActivity.class);
                intent.putExtra("from","vendor");
                intent.putExtra("id",item.getId());
                startActivity(intent);
            }

            @Override
            public void OnClickItemButtonListener3(int position) {
                final ServiceList.DataBean item = (ServiceList.DataBean) adapter.getItem(position);
                AlertDialog.Builder builder = new AlertDialog.Builder(VendorNoOverActivity.this);
                View view = LayoutInflater.from(VendorNoOverActivity.this).inflate(R.layout.fw_addprice_dia, null);
                final EditText addprice = (EditText) view.findViewById(R.id.dia_addprice);
                TextView nowprice = (TextView) view.findViewById(R.id.dia_nowprice);
                nowprice.setText(item.getTotalAmount()+"");
                Button cancel = (Button) view.findViewById(R.id.dia_addpricecancel);
                Button sure = (Button) view.findViewById(R.id.dia_addpricesure);
                builder.setView(view);
                final AlertDialog dialog = builder.create();
                cancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });
                sure.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String price = String.valueOf(addprice.getText());
                        if (!price.equals("")){
                            addPrice(price,item.getId());
                            dialog.dismiss();
                        }else {
                            Toast.makeText(VendorNoOverActivity.this, "请输入加价金额", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
                dialog.show();
            }

            @Override
            public void OnClickItemButtonListener4(int position) {

            }

            @Override
            public void OnClickItemButtonListener5(int position) {
                final ServiceList.DataBean item = (ServiceList.DataBean) adapter.getItem(position);
                AlertDialog.Builder builder = new AlertDialog.Builder(VendorNoOverActivity.this);
                View view = LayoutInflater.from(VendorNoOverActivity.this).inflate(R.layout.fw_addprice_dia, null);
                final EditText addprice = (EditText) view.findViewById(R.id.dia_addprice);
                TextView nowprice = (TextView) view.findViewById(R.id.dia_nowprice);
                nowprice.setText(item.getTotalAmount()+"");
                Button cancel = (Button) view.findViewById(R.id.dia_addpricecancel);
                Button sure = (Button) view.findViewById(R.id.dia_addpricesure);
                builder.setView(view);
                final AlertDialog dialog = builder.create();
                cancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });
                sure.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String price = String.valueOf(addprice.getText());
                        if (!price.equals("")){
                            addPrice(price,item.getId());
                            dialog.dismiss();
                        }else {
                            Toast.makeText(VendorNoOverActivity.this, "请输入加价金额", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
                dialog.show();
            }

            @Override
            public void OnClickItemButtonListener6(int position) {
                ServiceList.DataBean item = (ServiceList.DataBean) adapter.getItem(position);
                String id = item.getId();
                int makeupCount = item.getMakeupCount();
                String contactHouseNumber = item.getContactHouseNumber();
                String contactPhone = item.getContactPhone();
                String message = item.getMessage();
                Double makeupAmount = item.getMakeupAmount();
                String avatar = item.getAvatar();
                double amount = item.getAmount();
                int count = item.getCount();
                long buyTime = item.getBuyTime();
                Long commentTime = item.getCommentTime();
                String contactAddress = item.getContactAddress();
                String contactName = item.getContactName();
                String name = item.getName();
                String shopName = item.getShopName();
                String orderPayTime = item.getOrderPayTime();
                String orderPayType = item.getOrderPayType();
                String userMobile = item.getUserMobile();
                String orderCode = item.getOrderCode();
                double totalAmount = item.getTotalAmount();
                String shopAddress = item.getShopAddress();
                Intent intent = new Intent(VendorNoOverActivity.this,FWBookContentActivity.class);
                intent.putExtra("id",id);
                intent.putExtra("contactHouseNumber",contactHouseNumber);
                intent.putExtra("contactPhone",contactPhone);
                if (message.equals("")){}else {
                    intent.putExtra("message",message);
                }
                if (makeupAmount==null){}else {
                    intent.putExtra("makeupAmount",makeupAmount);
                }
                intent.putExtra("shopName",shopName);
                intent.putExtra("orderPayTime",orderPayTime);
                intent.putExtra("orderPayType",orderPayType);
                intent.putExtra("avatar",avatar);
                intent.putExtra("makeupCount",makeupCount);
                intent.putExtra("contactAddress",contactAddress);
                intent.putExtra("contactName",contactName);
                intent.putExtra("name",name);
                intent.putExtra("userMobile",userMobile);
                intent.putExtra("orderCode",orderCode);
                intent.putExtra("shopAddress",shopAddress);
                intent.putExtra("amount",amount);
                intent.putExtra("buyTime",buyTime);
                intent.putExtra("commentTime",commentTime);
                intent.putExtra("totalAmount",totalAmount);
                intent.putExtra("from",from);
                intent.putExtra("count",count);
                startActivity(intent);

            }
        });
        nooverlist.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                getNoOverList();
                nooverlist.onRefreshComplete();
                new FinishRefresh().execute();
            }
        });
    }

    private void initNoOverView() {
        nooverback = (ImageView) findViewById(R.id.vendor_noover_back);
        nooverlist = (PullToRefreshListView) findViewById(R.id.vendor_nooverlist);
        nodata = (ImageView) findViewById(R.id.vendernoover_nodata);
        backmain = (ImageView) findViewById(R.id.vendorno_backmain);
        backmain.setOnClickListener(this);
        nooverback.setOnClickListener(this);



    }

    //加价
    private void addPrice(String price, String id) {

        RequestParams params = new RequestParams(InternetAddressUtis.Url+InternetAddressUtis.GETADDSERVICE);
        params.addHeader("Content-Type","application/json");
        params.addHeader("token",token);
        params.addHeader("appId",appId);
        params.addHeader("userId",userId);
        JSONObject object = new JSONObject();
        object.put("orderId",id);
        object.put("amount",price);
        params.setBodyContent(object.toJSONString());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {

                JSONObject obj = JSON.parseObject(result);
                String status = obj.getString("status");
                if (status.equals("1")){
                    Toast.makeText(VendorNoOverActivity.this, "加价成功请等待对方回应", Toast.LENGTH_SHORT).show();
                }else if (status.equals("0")){
                    String failure = obj.getString("failure");
                    Toast.makeText(VendorNoOverActivity.this, "已申请加价，请等待对方回应", Toast.LENGTH_SHORT).show();
                }else {}
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ErrType.errType(VendorNoOverActivity.this,ex);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.vendor_noover_back:
                finish();
                break;
            case R.id.vendorno_backmain:
                startActivity(new Intent(VendorNoOverActivity.this, MainActivity.class));
                AppManager.getAppManager().finishAllActivity();
                break;
        }
    }

    private class FinishRefresh extends AsyncTask<Void, Void, Void> {
        @Override
        protected Void doInBackground(Void... params) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {

            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {

            adapter.notifyDataSetChanged();
            nooverlist.onRefreshComplete();
        }
    }
}
